package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.List;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;
import reactor.core.publisher.SinkOneSerialized;

import javax.management.BadAttributeValueExpException;
import javax.servlet.Registration;
import java.util.Arrays;

/**
 * 入住Service业务层处理
 * 
 * @author wd
 * @date 2025-05-17
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private IBedService bedService;
    @Autowired
    private IElderService elderService;
    @Autowired
    private IContractService contractService;
    @Autowired
    private ICheckInConfigService checkInConfigService;


    /**
     * 申请入住
     *
     * @param dto
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void apply(CheckInApplyDto dto) {

        String idCardNo = dto.getCheckInElderDto().getIdCardNo();

        // 判断老人是否入住
        Long countCheckIn = this.lambdaQuery().eq(CheckIn::getIdCardNo, idCardNo).eq(CheckIn::getStatus, 0).count();
        if (countCheckIn>0){
            throw new BaseException("老人已入住");
        }

        // 判断是否有床位
        Long bedId = dto.getCheckInConfigDto().getBedId();
        Bed bed = bedService.lambdaQuery().eq(Bed::getId,bedId).eq(Bed::getBedStatus,0).one();
        if (bed == null){
            throw new BaseException("床位不符合要求");
        }

        saveBed(bedId);

        // 更新或者新增老人
        Elder elder = saveOrUpdateElder(dto, idCardNo, bedId, bed);

        // 新增签约信息
        saveContract(dto, elder);

        // 新增入住信息
        CheckIn checkIn = saveCheckIn(dto, elder, idCardNo, bed);


        // 新增入住配置
        saveCheckInConfig(dto, checkIn);


    }

    private void saveCheckInConfig(CheckInApplyDto dto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(),checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        boolean saveCheckInConfig = checkInConfigService.save(checkInConfig);
        if (!saveCheckInConfig){
            throw new BaseException("新增入住配置失败");
        }
    }

    @NotNull
    private CheckIn saveCheckIn(CheckInApplyDto dto, Elder elder, String idCardNo, Bed bed) {
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(),checkIn);
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(idCardNo);
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(0);
        checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));
        boolean saveCheckin = this.save(checkIn);
        if (!saveCheckin){
            throw new BaseException("新增入住信息失败");
        }
        return checkIn;
    }

    private void saveContract(CheckInApplyDto dto, Elder elder) {
        Contract contract =new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(),contract);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
//        contract.setContractName(dto.getCheckInContractDto().getContractName());
        contract.setContractNumber("HT"+ CodeGenerator.generateContractNumber());// 合同编号
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(dto.getCheckInConfigDto().getEndDate());
//        contract.setAgreementPath(dto.getCheckInContractDto().getAgreementPath());
        int status = LocalDateTime.now().isBefore(contract.getStartDate())?  0 :
                LocalDateTime.now().isBefore(contract.getEndDate()) ? 1 : 2;//合同状态
        contract.setStatus(status);
        boolean saveContract = contractService.save(contract);
        if (!saveContract){
            throw new BaseException("新增合同信息失败");
        }
    }

    @NotNull
    private Elder saveOrUpdateElder(CheckInApplyDto dto, String idCardNo, Long bedId, Bed bed) {
        Elder elder = elderService.lambdaQuery().eq(Elder::getIdCardNo, idCardNo).one();
        if (elder==null) {
            elder = new Elder();
        }
        BeanUtils.copyProperties(dto.getCheckInElderDto(),elder);
        elder.setBedId(bedId);
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(4);
        boolean saveElder = elderService.save(elder);
        if (!saveElder){
            throw new BaseException("新增老人信息失败");
        }
        return elder;
    }

    private void saveBed(Long bedId) {
        // 更新床位信息
        Bed saveBed = new Bed();
        saveBed.setId(bedId);
        saveBed.setBedStatus(1);// 已入住

        boolean b = bedService.updateById(saveBed);
        if (!b){
            throw new BaseException("更新床位信息失败");
        }
    }


    /**
     * 查询入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {

        // 查询入住信息
        CheckIn checkIn = this.selectCheckInById(id);

        // 查询老人信息
        Elder elder = elderService.selectElderById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder,checkInElderVo);

        // 查询合同信息
        Contract contract = contractService.lambdaQuery().eq(Contract::getElderId, elder.getId()).one();

        // 查询入住配置信息
        CheckInConfig checkInConfig = checkInConfigService.lambdaQuery().eq(CheckInConfig::getCheckInId, checkIn.getId()).one();
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());

        // 转换家属列表
        // 将数据库的家属信息从json转换为实体
        List<ElderFamilyVo> elderFamilyVoList = JSONUtil.toList(JSONUtil.parseArray(checkIn.getRemark()), ElderFamilyVo.class);


        // 整合返回结果
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setContract(contract);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        return checkInDetailVo;
    }
}
